//
//  PYImageViewController.m
//  PictureYourself
//
//  Created by Daniel on 16/7/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "PYImageGalleryViewController.h"

static const int kImageCountPerRow = 4;

@implementation PYImageGalleryViewController

@synthesize tempCell;
@synthesize delegate = delegate_;

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIBarButtonItem* back_to_camera_button =
        [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self.delegate action:@selector(userIsDoneViewingGallery)] autorelease];
    
    self.toolbarItems = [NSArray arrayWithObjects:back_to_camera_button, nil];

    [self setEditing:FALSE];
}

-(void)viewDidAppear:(BOOL)animated
{
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)setEditing:(BOOL)editing
{
    UIBarButtonItem* button;
    
    button = editing ?
        [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(userCanceled)] autorelease] :
        [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(userRequestedEdit)] autorelease];
    
    self.navigationItem.rightBarButtonItem = button;
    editing_ = editing;
}

#pragma mark Table Data Binding

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger imageCount = [PYFileManager instance].imageCount;
    NSInteger rowCount = ceil((float)imageCount / (float)kImageCountPerRow);
    NSLog(@"%d rows in table\n", rowCount);
    return rowCount;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)index_path
{
    PYImageGalleryTableViewCell *cell = (PYImageGalleryTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"ThumbnailCell"];
    if(index_path.row == 0)
    NSLog(@"Cell requested for index: %@\n", index_path);
    
    if (cell == nil)
    {
        [[NSBundle mainBundle] loadNibNamed:@"PYImageGalleryTableViewCell" owner:self options:nil];
        cell = tempCell;
            //if(index_path.row == 0)
        NSLog(@"Created cell %p\n", cell);
        tempCell = nil;
    }
    
    cell.delegate = self;
    
    // Configure the cell...
    NSInteger imageCount = [PYFileManager instance].imageCount;
    NSUInteger imageIndex = index_path.row * 4;
    
    if (imageIndex >= imageCount)
    {
        NSLog(@"We are out of range, asking to start with photo %d but we only have %d", imageIndex, imageCount);
        return nil;
    }
    
    PYImageSelection* selection = [self getSelectionWithCellIndex:index_path.row];
    
    if(selection != nil)
    {
        [cell setSelectionForImage:0 selection:[selection objectIsSelectedAtIndex:0] animated:FALSE];
        [cell setSelectionForImage:1 selection:[selection objectIsSelectedAtIndex:1] animated:FALSE];
        [cell setSelectionForImage:2 selection:[selection objectIsSelectedAtIndex:2] animated:FALSE];
        [cell setSelectionForImage:3 selection:[selection objectIsSelectedAtIndex:3] animated:FALSE];
    }
    else
    {
        [cell setSelectionForImage:0 selection:FALSE animated:FALSE];
        [cell setSelectionForImage:1 selection:FALSE animated:FALSE];
        [cell setSelectionForImage:2 selection:FALSE animated:FALSE];
        [cell setSelectionForImage:3 selection:FALSE animated:FALSE];
    }
    
    NSUInteger lastImageIndex = imageIndex + kImageCountPerRow - 1;
    
    if(lastImageIndex > imageCount - 1)
        lastImageIndex = imageCount - 1;
    
    int image_view_tag = 1;
    
    while (imageIndex <= lastImageIndex)
    {
        UIImageView *imageView = (UIImageView*)[cell viewWithTag:image_view_tag++];
        NSDictionary* properties;
        CGImageRef imageRef = [[PYFileManager instance] copyThumbnailAtIndex:imageIndex :&properties];
        UIImageOrientation orientation = uiImageOrientationToApply((CFDictionaryRef)properties);
        
        if(imageRef != nil)
        {
            UIImage *image = [UIImage imageWithCGImage:imageRef scale:1.0 orientation:orientation];
            
            if(image != nil)
            {
                imageView.image = image;
                CGImageRelease(imageRef);
            }
            else
            {
                NSLog(@"Couldn't get UIImage for index %d\n", imageIndex);
                CGImageRelease(imageRef);
            }
        }
        else
        {
            NSLog(@"Couldn't get thumbnail for index %d\n", imageIndex);
        }
        
        imageIndex++;
    }

    return cell;
}

-(NSUInteger)globalImageIndexFrom:(NSUInteger)cell_index and:(NSUInteger)image_index
{
    return (cell_index * kImageCountPerRow) + image_index;
}

-(PYImageSelection*)getSelectionWithCellIndex:(NSUInteger)index
{
    PYImageSelection* selection;
    
    for (selection in selected_images_)
    {
        if(selection.cell_index != index)
        {
            if(selection.cell_index > index)
                break;
            
            continue;
        }
        
        return selection;
    }
    
    return nil;
}

-(BOOL)removeCellSelectionWithCellIndex:(NSUInteger)cell_index
{
    PYImageSelection* selection = [self getSelectionWithCellIndex:cell_index];
    
    if(selection == nil)
        return FALSE;
    
    [selected_images_ removeObject:selection];
    return TRUE;
}

#pragma mark User Actions

-(void)userRequestedEdit
{
    [self setEditing:TRUE];
}

-(void)userCanceled
{
    NSLog(@"User canceled");
    
    NSMutableSet* selections_to_remove = [NSMutableSet setWithCapacity:[selected_images_ count]];
    
    for (PYImageSelection* selection in selected_images_)
    {
        NSIndexPath* index_path = [NSIndexPath indexPathForRow:selection.cell_index inSection:0];
        
        PYImageGalleryTableViewCell* cell = (PYImageGalleryTableViewCell*)[self.tableView cellForRowAtIndexPath:index_path];
        NSLog(@"Retrieved cell %p\n", cell);
        
        if(cell != nil)
        {
            [cell setSelectionForImage:0 selection:FALSE animated:TRUE];
            [cell setSelectionForImage:1 selection:FALSE animated:TRUE];
            [cell setSelectionForImage:2 selection:FALSE animated:TRUE];
            [cell setSelectionForImage:3 selection:FALSE animated:TRUE];
        }
        
        [selections_to_remove addObject:selection];
    }
    
    for (PYImageSelection* selection_to_remove in selections_to_remove)
        [self removeCellSelectionWithCellIndex:selection_to_remove.cell_index];
    
    [self setEditing:FALSE];
}

-(void)thumbnailCellImageWasSelected:(PYImageGalleryTableViewCell*)cell :(NSUInteger)image_index
{
    if(!editing_)
    {
        UIViewController* image_view_controller = [[UIViewController alloc] init];
        UIImageView* image_view = [[UIImageView alloc] initWithFrame:image_view_controller.view.frame];
        [image_view_controller.view  setBackgroundColor:[UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1.0]];
        [image_view_controller.view addSubview:image_view];
        [image_view setBackgroundColor:[UIColor colorWithRed:0.7 green:0.4 blue:0.3 alpha:1.0]];
        NSIndexPath* cell_index = [self.tableView indexPathForCell:cell];
        NSInteger global_image_index = (cell_index.row * kImageCountPerRow) + image_index;
        image_view_controller.title = [NSString stringWithFormat:@"Image %d", global_image_index];
        UIImage* image = [[PYFileManager instance] getImageAtIndex:global_image_index];
        if(image == nil)
        {
            NSLog(@"!!!Couldn't get image\n");
            return;
        }
        image_view.image = image;
        [self.navigationController pushViewController:image_view_controller animated:TRUE];
        [image_view_controller release];
        [image_view release];
        // show full image
        [cell setSelectionForImage:image_index selection:FALSE animated:TRUE];
        return;
    }
    
    
    if(selected_images_ == nil)
        selected_images_ = [[NSMutableArray arrayWithCapacity:64] retain];
 
    NSIndexPath* index_path = [self.tableView indexPathForCell:cell];
    
    if(index_path == nil)
    {
        NSLog(@"!!!Couldn't get index path for cell %@\n", cell);
        return;
    }
    
    NSInteger cell_index = index_path.row;
    PYImageSelection* selection = [self getSelectionWithCellIndex:cell_index];
    BOOL selection_is_new = (selection == nil);
    
    if(selection_is_new)
    {
        selection = [[PYImageSelection alloc] init];
        selection.cell_index = cell_index;
    }
    
    [selection setSelectionForObjectAtIndex:image_index :TRUE];
    NSInteger insertion_index = 0;

    // Find the index to insert the new selection at
    for (PYImageSelection* iterator in selected_images_)
    {
        if(iterator.cell_index >= selection.cell_index)
            break;

        insertion_index++;
    }
    
    if(selection_is_new)
        [selected_images_ insertObject:selection atIndex:insertion_index];
    else
        [selected_images_ replaceObjectAtIndex:insertion_index withObject:selection];

    if(selection_is_new)
        [selection release];
}

-(void)thumbnailCellImageWasDeSelected:(id) cell:(NSUInteger)image_index
{
    if(selected_images_ == nil)
        return;
    
    NSInteger cell_index = [self.tableView indexPathForCell:cell].row;
    [self removeCellSelectionWithCellIndex:cell_index];
}

@end
